{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "multiclass-rock_paper_scissors.ipynb",
      "provenance": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/lmoroney/tfbook/blob/master/chapter3/multiclass.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zX4Kg8DUTKWO",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Zngoz-UdPDga",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "try:\n",
        "  # %tensorflow_version only exists in Colab.\n",
        "  %tensorflow_version 2.x\n",
        "except Exception:\n",
        "  pass"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "it1c0jCiNCIM",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "!wget --no-check-certificate \\\n",
        "    https://storage.googleapis.com/learning-datasets/rps.zip \\\n",
        "    -O /tmp/rps.zip\n",
        "  \n",
        "!wget --no-check-certificate \\\n",
        "    https://storage.googleapis.com/learning-datasets/rps-test-set.zip \\\n",
        "    -O /tmp/rps-test-set.zip"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "PnYP_HhYNVUK",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import os\n",
        "import zipfile\n",
        "\n",
        "local_zip = '/tmp/rps.zip'\n",
        "zip_ref = zipfile.ZipFile(local_zip, 'r')\n",
        "zip_ref.extractall('/tmp/')\n",
        "zip_ref.close()\n",
        "\n",
        "local_zip = '/tmp/rps-test-set.zip'\n",
        "zip_ref = zipfile.ZipFile(local_zip, 'r')\n",
        "zip_ref.extractall('/tmp/')\n",
        "zip_ref.close()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "MrxdR83ANgjS",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "rock_dir = os.path.join('/tmp/rps/rock')\n",
        "paper_dir = os.path.join('/tmp/rps/paper')\n",
        "scissors_dir = os.path.join('/tmp/rps/scissors')\n",
        "\n",
        "print('total training rock images:', len(os.listdir(rock_dir)))\n",
        "print('total training paper images:', len(os.listdir(paper_dir)))\n",
        "print('total training scissors images:', len(os.listdir(scissors_dir)))\n",
        "\n",
        "rock_files = os.listdir(rock_dir)\n",
        "print(rock_files[:10])\n",
        "\n",
        "paper_files = os.listdir(paper_dir)\n",
        "print(paper_files[:10])\n",
        "\n",
        "scissors_files = os.listdir(scissors_dir)\n",
        "print(scissors_files[:10])"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "jp9dLel9N9DS",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "%matplotlib inline\n",
        "\n",
        "import matplotlib.pyplot as plt\n",
        "import matplotlib.image as mpimg\n",
        "\n",
        "pic_index = 2\n",
        "\n",
        "next_rock = [os.path.join(rock_dir, fname) \n",
        "                for fname in rock_files[pic_index-2:pic_index]]\n",
        "next_paper = [os.path.join(paper_dir, fname) \n",
        "                for fname in paper_files[pic_index-2:pic_index]]\n",
        "next_scissors = [os.path.join(scissors_dir, fname) \n",
        "                for fname in scissors_files[pic_index-2:pic_index]]\n",
        "\n",
        "for i, img_path in enumerate(next_rock+next_paper+next_scissors):\n",
        "  #print(img_path)\n",
        "  img = mpimg.imread(img_path)\n",
        "  plt.imshow(img)\n",
        "  plt.axis('Off')\n",
        "  plt.show()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "LWTisYLQM1aM",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import tensorflow as tf\n",
        "import keras_preprocessing\n",
        "from keras_preprocessing import image\n",
        "from keras_preprocessing.image import ImageDataGenerator\n",
        "\n",
        "TRAINING_DIR = \"/tmp/rps/\"\n",
        "training_datagen = ImageDataGenerator(\n",
        "      rescale = 1./255,\n",
        "\t    rotation_range=40,\n",
        "      width_shift_range=0.2,\n",
        "      height_shift_range=0.2,\n",
        "      shear_range=0.2,\n",
        "      zoom_range=0.2,\n",
        "      horizontal_flip=True,\n",
        "      fill_mode='nearest')\n",
        "\n",
        "VALIDATION_DIR = \"/tmp/rps-test-set/\"\n",
        "validation_datagen = ImageDataGenerator(rescale = 1./255)\n",
        "\n",
        "train_generator = training_datagen.flow_from_directory(\n",
        "\tTRAINING_DIR,\n",
        "\ttarget_size=(150,150),\n",
        "\tclass_mode='categorical'\n",
        ")\n",
        "\n",
        "validation_generator = validation_datagen.flow_from_directory(\n",
        "\tVALIDATION_DIR,\n",
        "\ttarget_size=(150,150),\n",
        "\tclass_mode='categorical'\n",
        ")\n",
        "\n",
        "model = tf.keras.models.Sequential([\n",
        "    # Note the input shape is the desired size of the image 150x150 with 3 bytes color\n",
        "    # This is the first convolution\n",
        "    tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(150, 150, 3)),\n",
        "    tf.keras.layers.MaxPooling2D(2, 2),\n",
        "    # The second convolution\n",
        "    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n",
        "    tf.keras.layers.MaxPooling2D(2,2),\n",
        "    # The third convolution\n",
        "    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n",
        "    tf.keras.layers.MaxPooling2D(2,2),\n",
        "    # The fourth convolution\n",
        "    tf.keras.layers.Conv2D(128, (3,3), activation='relu'),\n",
        "    tf.keras.layers.MaxPooling2D(2,2),\n",
        "    # Flatten the results to feed into a DNN\n",
        "    tf.keras.layers.Flatten(),\n",
        "    tf.keras.layers.Dropout(0.5),\n",
        "    # 512 neuron hidden layer\n",
        "    tf.keras.layers.Dense(512, activation='relu'),\n",
        "    tf.keras.layers.Dense(3, activation='softmax')\n",
        "])\n",
        "\n",
        "\n",
        "model.summary()\n",
        "\n",
        "model.compile(loss = 'categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n",
        "\n",
        "history = model.fit(train_generator, epochs=25, validation_data = validation_generator, verbose = 1)\n",
        "\n",
        "model.save(\"rps.h5\")\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "aeTRVCr6aosw",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import matplotlib.pyplot as plt\n",
        "acc = history.history['accuracy']\n",
        "val_acc = history.history['val_accuracy']\n",
        "loss = history.history['loss']\n",
        "val_loss = history.history['val_loss']\n",
        "\n",
        "epochs = range(len(acc))\n",
        "\n",
        "plt.plot(epochs, acc, 'r', label='Training accuracy')\n",
        "plt.plot(epochs, val_acc, 'b', label='Validation accuracy')\n",
        "plt.title('Training and validation accuracy')\n",
        "plt.legend(loc=0)\n",
        "plt.figure()\n",
        "\n",
        "\n",
        "plt.show()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ZABJp7T3VLCU",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import numpy as np\n",
        "from google.colab import files\n",
        "from keras.preprocessing import image\n",
        "\n",
        "uploaded = files.upload()\n",
        "\n",
        "for fn in uploaded.keys():\n",
        " \n",
        "  # predicting images\n",
        "  path = fn\n",
        "  img = image.load_img(path, target_size=(150, 150))\n",
        "  x = image.img_to_array(img)\n",
        "  x = np.expand_dims(x, axis=0)\n",
        "\n",
        "  images = np.vstack([x])\n",
        "  classes = model.predict(images, batch_size=10)\n",
        "  print(fn)\n",
        "  print(classes)"
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}
